package top.rish.minfire.config;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateNotFoundException;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.exception.StatusException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.view.freemarker.FreemarkerRender;

import java.io.StringWriter;
import java.util.HashMap;
@Component(index = 0)
public class Error404Filter implements Filter {
    private static final String NOT_FOUND_PAGE = "/common/error/404.html";
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
        } catch (StatusException e){
            if (e.getCode() == 404) {
                //如果不需要再继承，就可以当 404 处理并返回了
                Configuration provider = FreemarkerRender.global().getProvider();
                Configuration providerOfDebug = FreemarkerRender.global().getProviderOfDebug();
                Template template = null;
                if (providerOfDebug != null) {
                    try {
                        template = providerOfDebug.getTemplate(NOT_FOUND_PAGE, Solon.encoding());
                    } catch (TemplateNotFoundException ex) {
                        //忽略不计
                    }
                }
                if (template == null) {
                    template = provider.getTemplate(NOT_FOUND_PAGE, Solon.encoding());
                }
                HashMap<Object, Object> hashMap = new HashMap<>();
                StringWriter out = new StringWriter();
                // 输出流
                template.process(hashMap, out);
                ctx.contentType("text/html;charset=utf-8");
                ctx.output(out.toString());
                return;
            }
        }
    }
}